< previous page page_299 next page >

Page 299
Loading and Unloading Controls at Runtime
In other chapters, you learned how to add controls to forms while you are in the design environment. In the preceding section, you even learned how you can create control arrays to handle processing of multiple controls easily in code. However, nothing you have seen yet shows you how to add and remove controls at runtime.
tip.gif
If you plan to add menu items at runtime, place the menu item array at the bottom of a menu. By doing this, you cause the menu to expand after the fixed items so that the user is not confused by items changing positions within the menu.

note.gif You can hide and show controls at runtime by setting the Visible property appropriately. However, you must create these controls before you can use them. Showing and hiding controls is not the same as adding new controls. square.gif

The only way to add controls at runtime is to add elements of a control array. You cannot add a new individual control because you wouldn't have any event code to handle any events triggered by the users. Because event code has already been defined for a control array at designtime, new elements of the array are automatically handled.
CAUTION
If you use If or Select statements to process code for different index values, you should make sure that your code works for all array elements, even new ones that might have been added at runtime. LBound and UBound help you accomplish this task; however, keep in mind that the indices in a control array may not be numbered sequentially.

Creating the First Element of a Control Array
Because any new control that you add at runtime must be part of a control array, you must create the array, or at least its first element, at designtime. For many arrays, you will want only a single element to be created at design time. This gives you the maximum flexibility to add and remove controls during program execution. To create the first element of a control array, follow these steps:
1. Draw the control on your form.
2. Set the Name property of the control.
3. Set the Index property of the control to an integer value (usually 0).
Note that setting the Index property to something other than an empty value creates a control array. If you copy and paste a control, Visual Basic sets the Index property for you.

 
< previous page page_299 next page >